<template>
  <a-modal
    v-model:visible="visible"
    title="分配接口"
    @ok="handleOk"
    ok-text="确定"
    cancel-text="取消"
  >
    <a-form
      ref="formRef"
      :model="modelRef"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <a-form-item label="权限名称" name="name">
        {{ item.name }}
      </a-form-item>
      <a-form-item label="Api接口" name="apiIds">
        <a-tree
          style="min-height: 80px;max-height: 350px; overflow: auto"
          checkable
          :tree-data="apiTree"
          :replaceFields="replaceFields"
          v-model:checkedKeys="modelRef.apiIds"
          default-expand-all
          :show-line="true"
          :checkStrictly="true"
        >
          <template #title="value">
            {{ value.name }} [ID:{{ value.merch_api_id }}]
          </template>
        </a-tree>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
import { assignAuth } from "@/api/menu/merch/List";
import { toRefs, reactive, defineComponent } from "vue";
import { notice } from "@/config";
import { TreeSelect } from "ant-design-vue";
const SHOW_PARENT = TreeSelect.SHOW_PARENT;
export default defineComponent({
  setup(props, { emit }) {
    let state = reactive({
      visible: false,
      apiTree: [],
      replaceFields: {
        children: "children",
        title: "name",
        key: "merch_api_id",
      },
      formRef: {},
      item: {},
    });
    let modelRef = reactive({
      apiIds: [],
      merch_menu_id: 0,
    });

    // 显示对话框
    const show = (apiTree, item) => {
      state.apiTree = apiTree;
      state.item = item;

      modelRef.apiIds = item.apiIds;
      state.visible = state.visible ? false : true;
      modelRef.merch_menu_id = item.merch_menu_id;
    };

    const handleOk = () => {
      state.formRef.validate().then(() => {
        assignAuth({
          merch_menu_id: modelRef.merch_menu_id,
          apiIds: modelRef.apiIds.checked
            ? modelRef.apiIds.checked
            : modelRef.apiIds,
        }).then((res) => {
          emit("okCallback", res);
          notice(res.status == 200 ? "success" : "error", res.message);
          state.visible = false;
        });
      });
    };

    return {
      show,
      handleOk,
      ...toRefs(state),
      labelCol: {
        span: 6,
      },
      wrapperCol: {
        span: 16,
      },
      modelRef,
      SHOW_PARENT,
    };
  },
});
</script>
